﻿package ahxu.crawler;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class CrawlServiceProvider implements ApplicationContextAware{
private static CrawlServiceProvider esnsCoreServiceProvider = null;
	
	private static ApplicationContext classPathXmlApplicationContext = null;
	
	private static String[] contextXml = new String[] {
		"classpath*:resources/*-spring-core.xml",
		"classpath*:resources/crawl/*-spring-core.xml",
	};

	private CrawlServiceProvider() {
		super();
		initContext();
	}
	
	private CrawlServiceProvider(ApplicationContext context) {
		super();
		classPathXmlApplicationContext=context;
	}
	

	private void initContext() {
		classPathXmlApplicationContext = 
			new ClassPathXmlApplicationContext(contextXml);
	}
	
	public static CrawlServiceProvider getInstance() {
		if(esnsCoreServiceProvider==null) {
			esnsCoreServiceProvider = new CrawlServiceProvider();
		}
		return esnsCoreServiceProvider;
	}
	
	public static CrawlServiceProvider getInstance(ApplicationContext context) {
		if(esnsCoreServiceProvider==null) {
			esnsCoreServiceProvider = new CrawlServiceProvider(context);
		}
		return esnsCoreServiceProvider;
	}
	
	public ICrawlerResutlDao getResultDao(){
		return getCommonBean("crawlResultDao",DefaultCrawlerResultDao.class);
	}
	
	public CrawlerManager getCrawlerManager(){
		return getCommonBean("crawlerManager",CrawlerManager.class);
	}
	
	
	
	 @SuppressWarnings("unchecked")
	private <T> T getCommonBean(String name,Class<T> type){
		return (T)classPathXmlApplicationContext.getBean(name);
	}

	public void setApplicationContext(ApplicationContext context) throws BeansException {
		classPathXmlApplicationContext=context;
		
	}
}
